package com.yuneec.rcService;

import com.yuneec.droneservice.command.CommandListener;
import com.yuneec.droneservice.command.MAV_RC_ERROR_CODE;
import com.yuneec.droneservice.request.IResponse;

import java.lang.ref.WeakReference;

public abstract class RcCallBack<T> {
    public void onSuccess(T data) {
    }

    public void onFail() {
    }

    public void onTimeout() {
    }

    public static class RCC<T> extends CommandListener<T> {
        private WeakReference<RcCallBack<T>> callBack;

        public RCC(RcCallBack<T> cb) {
            this.callBack = new WeakReference<>(cb);
        }

        @Override
        public void onTimeout() {
            RcCallBack<T> cb = callBack.get();
            if (cb != null) {
                cb.onTimeout();
            }
        }

        @Override
        public void onSuccess(IResponse<T> response) {
            RcCallBack<T> cb = callBack.get();
            if (cb == null) {
                return;
            }
            if (response == null || response.getCode() != MAV_RC_ERROR_CODE.MAV_RC_ERR_SUCCESS) {
                cb.onFail();
            } else {
                cb.onSuccess(response.getParam());
            }
        }

        @Override
        public void onError(int errorCode) {
            RcCallBack<T> cb = callBack.get();
            if (cb != null) {
                cb.onFail();
            }
        }
    }
}
